import * as React from 'react';
import {ComponentDecorator, connect} from 'react-redux';

import {IDesign} from './types/IDesign';
import {AppState} from './store';
import {DesignNamesState} from './store/designNamesReducer';
import TabTitlePane from './panes/tab/TabTitlePane';
import DesignerPane from './panes/designer/DesignerPane';

import './App.css';

export interface AppMergedProps {
  designs: IDesign[];
  designNames: DesignNamesState;
  activeDesign: IDesign;
}

type AppProps = AppMergedProps;

function mapStateToProps(state: AppState): AppMergedProps {
  const {designIdsState, designsState, designNamesState, activeDesignState} = state;

  const designs = designIdsState.map(designId => {
    return designsState[designId];
  });

  const activeDesignId = activeDesignState.active;
  const activeDesign = designsState[activeDesignId] || designsState[designIdsState[0]];

  return {
    designs,
    designNames: designNamesState,
    activeDesign
  };
}

class App extends React.Component<AppProps, undefined> {
  render() {
    const {designs, designNames, activeDesign} = this.props;
    if (!designs || designs.length === 0 || !this.props.activeDesign) {
      return null;
    }
    return (
      <div className="App">
        <TabTitlePane designs={designs} designNames={designNames} activeDesign={activeDesign}/>
        <div className="App-contents">
          {this.renderDesigner(this.props.activeDesign)}
        </div>
      </div>
    );
  }

  private renderDesigner(design: IDesign): JSX.Element | null {
    return (
      <DesignerPane key={design.id} design={design}/>
    );
  }
}

type AppDecorator = ComponentDecorator<AppMergedProps, undefined>;
const componentDecorator: AppDecorator = connect(mapStateToProps);
export default componentDecorator(App);
